package com.ovopark.organize.server.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ovopark.organize.server.model.entity.RentRule;
import com.ovopark.organize.server.model.help.DepartmentHelp;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.MessageSource;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

public class LogUtils {
	private static Logger log = LoggerFactory.getLogger(LogUtils.class);
	public static String getRemoteIp(HttpServletRequest request) {
		String realIp = request.getHeader("X-Real-IP");
		String remoteIp = request.getHeader("x-forwarded-for"); // nginx反向代理
		if (org.apache.commons.lang3.StringUtils.isNotEmpty(realIp)) {
			log.info("X-Real-IP:" + realIp);
//			return realIp;
		}
		if (org.apache.commons.lang3.StringUtils.isNotEmpty(remoteIp)) {
			log.info("x-forwarded-for:" + remoteIp);
			// 截取第一个
			// TODO 这里无法防止伪造x-forwarded-for，要防止伪造需要配置第一台nginx的ip。取ip前面的一个地址
			if (remoteIp.contains(",")) {
				remoteIp = remoteIp.split(",")[0].trim();
			}
			return remoteIp;
		} else {
			return request.getRemoteAddr();
		}
	}
	
	@SuppressWarnings("rawtypes")
	public static JSONObject getparameters(HttpServletRequest request) {
		Enumeration parameters = request.getParameterNames();
		Map<String, String> map = new HashMap<String, String>();
		while(parameters.hasMoreElements()) {
			String paramName = (String)parameters.nextElement();
			String value = request.getParameter(paramName);
			map.put(paramName, value);
		}
		String json = JSON.toJSONString(map);//map转String
		return JSONObject.parseObject(json);
	}
	
	public static String getPlatform(HttpServletRequest request) {
		String userAgent = request.getHeader("User-Agent");
//		System.out.println("UA:===========" + userAgent);
		String platform = null;
		if (userAgent != null) {
			// 安卓使用okhttp框架
			if (userAgent.contains("Android") || userAgent.contains("okhttp")) {
				platform = "Android";
			} else if (userAgent.contains("iOS")) {
				platform = "iOS";
			} else {
				// 获取客户端浏览器
				platform = "web";
				/*StringTokenizer st = new StringTokenizer(userAgent, ";");
				st.nextToken();
				platform = st.nextToken();*/
			}
		} else {
			// TODO 没有默认UA，是自定义客户端传来的，需定义各个客户端的标记
			platform = "unknown";
		}
		return platform;
	}


	public static String getValueByMessageSource(String key, String i18nParam, MessageSource messageSource, Locale locale) {
		List<String> needMessage = new ArrayList<>();
		needMessage.add("deptType");
		needMessage.add("region");
		needMessage.add("timeZone");
		needMessage.add("closeReasons");
		needMessage.add("openStatus");
		//批量更新中 巡店线路 回放服务器 summerTime rentPaymentInformation  时区 门店状态 关闭类型 值 都需要 国际化
		if(needMessage.contains(key)){
			switch (key){
				case "closeReasons":
					i18nParam = "department.export.status.close."+i18nParam;
					break;
				case "openStatus":
					String status = DepartmentHelp.getOpenstatusName(Integer.valueOf(i18nParam.trim()));
					i18nParam = "department.export.status."+status;
					break;
				case "summerTime":
					i18nParam = "department.export."+i18nParam;
					break;
				default:
					i18nParam = "department.export."+key+"."+i18nParam;
					break;
			}
			i18nParam = messageSource.getMessage(i18nParam, null, locale);
		}

		if(key.equals("rentPaymentInformation") && StringUtils.isNotEmpty(i18nParam)){
			//{"firstLeaseTimeStr":"2022-10-11 00:00:00","rentCycle":"3","rentReminder":"1","earlyReminderDays":"3"}
			RentRule rentRule = JSONObject.parseObject(i18nParam,RentRule.class);
			String firstLeaseTimeStr = messageSource.getMessage("department.export.firstLeaseTimeStr", rentRule.getFirstLeaseTimeStr().split(","), locale);
			String rentCycle  =  messageSource.getMessage("department.export.rentCycle."+rentRule.getRentCycle(), null, locale);
			String rentReminder  ="";
			if(rentRule.getRentCycle() !=null){
				 rentReminder  = messageSource.getMessage("department.export."+rentRule.getRentReminder(), null, locale);
			}
			String earlyReminderDays ="";
			if(rentRule.getEarlyReminderDays() !=null){
				 earlyReminderDays = messageSource.getMessage("department.export.earlyReminderDays", rentRule.getEarlyReminderDays().toString().split(","), locale);
			}
			i18nParam =  firstLeaseTimeStr+"/"+rentCycle+"/"+rentReminder+"/"+earlyReminderDays;
		}

		if(key.equals("summerTime") && StringUtils.isNotEmpty(i18nParam) && i18nParam.contains("/")){
			//夏令时  ok
			List<String> summerTimeList = Arrays.asList(i18nParam.split("/"));
			String summerTimeMain = messageSource.getMessage("department.export.isSummerTime", null, locale);
			String summerTimeRemind = messageSource.getMessage("department.export."+summerTimeList.get(0), null, locale);
			String summerTimeStr = "";
			if(StringUtils.isNotEmpty(summerTimeList.get(1))){
				 summerTimeStr = messageSource.getMessage("department.export.summerTimeStart", null, locale)+summerTimeList.get(1);
			}
			String summerTimeEnd = "";
			if(StringUtils.isNotEmpty(summerTimeList.get(2))){
				 summerTimeEnd  = messageSource.getMessage("department.export.summerTimeEnd", null, locale)+summerTimeList.get(2);
			}
			i18nParam =summerTimeMain+":"+ summerTimeRemind+" "+summerTimeStr+" "+summerTimeEnd;

		}

		return i18nParam;
	}


	public static String getBatchMessage(String description, String i18nParam,String i18nKey, MessageSource messageSource, Locale locale) {

		List<String> fileName = Arrays.asList(description.split(","));
		String key = fileName.get(1);
		List<String> newFileName = new ArrayList<>();
		newFileName.add(fileName.get(0));
		//批量更新中 巡店线路 回放服务器 summerTime rentPaymentInformation  时区 门店状态 关闭类型 值 都需要 国际化
		String fieldValue  = LogUtils.getValueByMessageSource(key,i18nParam,messageSource,locale);
		if(key.equals("storeArea") ||key.equals("closeReasons") || key.equals("tradingArea") || key.equals("address") || key.equals("rental") || key.equals("closeContent") ){
			key = "department.export."+key;
		}else {
			key = "department.batch."+key;
		}
		String keyName = messageSource.getMessage(key, null, locale);
		newFileName.add(keyName);
		newFileName.add(fieldValue);
	   description =	messageSource.getMessage(i18nKey, newFileName.toArray(), locale);
		return description;
	}

}
